﻿namespace PropOnline.Models.Validation
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Globalization;
    using System.Linq;
    using System.Web.Mvc;
    using PropOnline.Models;
    using PropOnline.ViewModels.Tasacion;

    /// <summary>
    /// Se require el atributo solo cuando otra propiedad tiene el valor dado.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class RequiredOnOtherPropertyValueAttribute : ValidationAttribute, IClientValidatable
    {
        private string otherPropertyName;        
        private string otherPropertyValue;

        public RequiredOnOtherPropertyValueAttribute(string otherPropertyName, string otherPropertyValue)
        {
            this.otherPropertyName = otherPropertyName;
            this.otherPropertyValue = otherPropertyValue;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "required",
                ErrorMessage = this.ErrorMessageString
            };            

            yield return rule;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                var property = validationContext.ObjectInstance.GetType().GetProperty(this.otherPropertyName);               

                var propertyValue = property.GetValue(validationContext.ObjectInstance, null);

                if (propertyValue != null)
                {
                    if (propertyValue.ToString() == this.otherPropertyValue)
                    {
                        return new ValidationResult(this.ErrorMessageString);
                    }
                }                                
            }

            return ValidationResult.Success;            
        }
    }
}